package com.module.overview.ui.historicalDataDetails.provider

import android.graphics.Typeface
import com.chad.library.adapter.base.provider.BaseItemProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.common.app.data.bean.overView.HistoryDetailsModel
import com.common.app.utls.TimeUtils
import com.common.base.app.extras.doOnIOThread
import com.common.base.app.extras.doOnUiThread
import com.common.base.app.extras.no
import com.common.base.app.extras.yes
import com.common.base.utils.JsonUtils
import com.common.base.utils.SpanUtils
import com.common.base.utils.ViewUtils
import com.common.base.utils.ViewUtils.getString
import com.module.ble.data.bean.CusChartData
import com.module.ble.repo.SleepInfoRepo
import com.module.ble.utils.AllCardTypeConfig
import com.module.ble.widget.HdCandlestickChart
import com.module.ble.widget.SleepOptimalRangeProgressBar
import com.module.overview.R

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2028/08/08
 *
 * 描述：睡眠总时长卡片
 *
 * 修订历史：
 *
 */
class OvHdSleepTotalDurationCardProvider(
    val mType: Int = 1,
    override val itemViewType: Int = AllCardTypeConfig.TYPE_CARD_HD_SLEEP_TOTAL_SLEEP_DURATION,
    override val layoutId: Int = R.layout.overview_hd_total_sleep_duration_crad_provider
) : BaseItemProvider<HistoryDetailsModel>() {

    private var candlestickChart: HdCandlestickChart? = null

    // 设置数据
    private val stressData = mutableListOf<CusChartData>()
    private val exStressData = mutableListOf<CusChartData>()
    private var averageDataValues = mutableListOf<CusChartData>()

    val touchValueSplicing = "${getString(R.string.pickerview_minutes)}"

    val touchValueHint = when(mType){
        3->"${getString(R.string.common_month_unit)}"
        else->"${getString(R.string.common_week_unit)}"
    }

    private var maxStages = 100f

    init {
    }

    override fun convert(helper: BaseViewHolder, item: HistoryDetailsModel) {
        candlestickChart?.showYMiddleLine(false)
        candlestickChart?.setXAxisSolidLineEnabled(true)

        // 设置自定义X轴时间标签
        var timeLabels: Map<Int, String> = mapOf()

        when(mType){
            1->{//周
                candlestickChart?.setBarSpacing(25f)
                timeLabels =  mapOf(
                    0 to "一",    // 第1条数据下方显示"一"
                    1 to "二",    // 第2条数据下方显示"二"
                    2 to "三",   // 第3条数据下方显示"三"
                    3 to "四",   // 第4条数据下方显示"四"
                    4 to "五",   // 第5条数据下方显示""五"
                    5 to "六",    // 第6条数据下方显示"五"
                    6 to "七",    // 第7条数据下方显示"七"
//            19 to "30",    // 第20条数据下方显示"30"
                )
            }
            2->{//月
                candlestickChart?.setBarSpacing(5f)
                timeLabels = mapOf(
                    0 to "一",    // 第1条数据下方显示"一"
                    1 to "二",    // 第2条数据下方显示"二"
                    2 to "三",   // 第3条数据下方显示"三"
                    3 to "四",   // 第4条数据下方显示"四"
                    4 to "五",   // 第5条数据下方显示""五"
                    5 to "六",    // 第6条数据下方显示"五"
                    6 to "七",    // 第7条数据下方显示"七"
//            19 to "30",    // 第20条数据下方显示"30"
                )
            }
            3->{//年
                candlestickChart?.setBarSpacing(5f)
                timeLabels = mapOf(
                    0 to "1",
                    1 to "2",
                    2 to "3",
                    3 to "4",
                    4 to "5",
                    5 to "6",
                    6 to "7",
                    7 to "8",
                    8 to "9",
                    9 to "10",
                    10 to "11",
                    11 to "12",
                )
            }
        }

        stressData.clear()
        // 设置动态数量的数据
        for (i in 0 until when(mType){
            2->30
            3->12
            else->7
        }) {
            stressData.add(CusChartData(
                createdTime = 0,
                minValue = 0f,
                mValue = (1..7).random().toFloat(),
                dayNum = 0
            ))
        }

        averageDataValues.clear()
        stressData.forEach {
            averageDataValues.add(
                CusChartData(
                    createdTime = it.createdTime,
                    minValue = it.minValue,
                    mValue = (it.minValue+((it.mValue-it.minValue)/2)),
                    dayNum = 0
                )
            )
        }

        exStressData.clear()
        // 设置动态数量的Ex数据
        for (i in 0 until when(mType){
            2->30
            3->12
            else->7
        }) {
            exStressData.add(CusChartData(
                createdTime = 0,
                minValue = 0f,
                mValue = 0f,
                dayNum = 0
            ))
        }

        exStressData[4].mValue = stressData[4].mValue+2f

        val maxMValue = stressData.maxByOrNull { it.mValue }?.mValue?:100f
        val maxExMValue = exStressData.maxByOrNull { it.mValue }?.mValue?:100f
        maxStages = if(maxMValue>maxExMValue) maxMValue else maxExMValue

        // 设置Y轴阶段
        candlestickChart?.setYAxisStages(
            floatArrayOf(0f, (maxStages/2).toInt().toFloat(), maxStages), // 阶段分界点
        )

        candlestickChart?.setBasicValue((1..7).random().toFloat())
        candlestickChart?.setData(stressData,exStressData)
//        candlestickChart?.setAverageData(averageDataValues)

        // 设置自定义X轴时间标签
        candlestickChart?.setCustomTimeLabels(timeLabels)

        // 设置触摸监听
        candlestickChart?.setOnBarTouchListener(object : HdCandlestickChart.OnBarTouchListener {
            override fun onBarTouched(barIndex: Int, minValue: Float, maxValue: Float, timeLabel: String, exValue: Float) {
                // 处理触摸事件
//                Log.d("CandlestickChart", "触摸到柱子: 索引=$barIndex,触摸到: $timeLabel, 值: $minValue")
                val sleepHint = "${getString(R.string.common_sleep_hint)}:"
                val minutesHint = getString(R.string.common_minutes_hint)
                val napSleepTempStr = "      ${getString(R.string.common_sleep_nap_hint)}:"

                val spanBuilder = SpanUtils.create()
                spanBuilder.addForeColorSection(sleepHint, ViewUtils.getColor(R.color.c_7f7f7f))
                    .setAbsSize(sleepHint, 14)
                    .setStyle(sleepHint, Typeface.NORMAL)
                spanBuilder.addSection("${maxValue.toInt()}")
                spanBuilder.addForeColorSection(minutesHint, ViewUtils.getColor(R.color.c_7f7f7f))
                    .setAbsSize(minutesHint, 14)
                    .setStyle(minutesHint, Typeface.NORMAL)

                (exValue >0).yes {
                    spanBuilder.addForeColorSection(napSleepTempStr, ViewUtils.getColor(R.color.c_7f7f7f))
                        .setAbsSize(napSleepTempStr, 14)
                        .setStyle(napSleepTempStr, Typeface.NORMAL)
                    spanBuilder.addSection("${exValue.toInt()}")
                    spanBuilder.addForeColorSection(minutesHint, ViewUtils.getColor(R.color.c_7f7f7f))
                        .setAbsSize(minutesHint, 14)
                        .setStyle(minutesHint, Typeface.NORMAL)
                }
                spanBuilder.showIn(helper.getView(R.id.tvTouchValue))

                helper.setText(R.id.tvTouchValueHint, when(mType){
                    2->"$timeLabel"
                    3->"$timeLabel$touchValueHint"
                    else->"$touchValueHint$timeLabel"
                })
                helper.setVisible(R.id.totalTouchValue, true)
                helper.setVisible(R.id.totalLowest, false)
                helper.setVisible(R.id.totalAverage, false)
                helper.setVisible(R.id.totalHighest, false)
            }

            override fun onTouchReleased() {
                // 处理触摸释放事件
                helper.setVisible(R.id.totalTouchValue, false)
                helper.setVisible(R.id.totalLowest, true)
                helper.setVisible(R.id.totalAverage, true)
                helper.setVisible(R.id.totalHighest, true)
            }
        })

        getOneWeekData(item.timePair?.first?:0, item.timePair?.second?:0)
    }


    override fun onViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {
        candlestickChart = viewHolder.getView(R.id.candlestickChart)
        candlestickChart?.setBarRounding(enableTop = true, enableBottom = false)
        super.onViewHolderCreated(viewHolder, viewType)
    }

    //查出一周的数据
    fun getOneWeekData(startTime:Long,endTime:Long){
        if (startTime<=0 || endTime<=0) return
        doOnIOThread {
            SleepInfoRepo.instance.findByTimeRangeByNight(startTime, endTime)?.let { listIt->
                val listItStr = JsonUtils.toJson(listIt)

                listIt.sortedBy { it.createdTime }//按时间排序（升序）

                doOnUiThread {
                }

            }
        }
    }
}